"use strict";
// 变量定义
var gulp = require('gulp'),
    autoprefixer = require('gulp-autoprefixer'),    //CSS3自动添加前缀
    browserSync = require('browser-sync'),          //文件自动同步
    sass = require('gulp-sass'),                    //SCSS自动编译
    imagemin = require('gulp-imagemin'),            //IMG压缩插件
    pngquant = require('imagemin-pngquant'),        //PNG工具
    jshint = require('gulp-jshint'),                //JavaScript自动检测工具
    minifyCss = require('gulp-minify-css'),         //CSS压缩插件
    uglify = require('gulp-uglify'),                //Js代码混淆工具
    del = require('del');

// 清理CSS文件
gulp.task('cleanCss', function (cb) {
    del(['src/stylesheets/*.css'], cb)
});

// 图片压缩
gulp.task('img-mini', function () {
    gulp.src('src/images/**/*.png')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('dist/images/'));
});

// JS脚本语法检查
gulp.task('lint', function () {
    return gulp.src('src/javascripts/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});

// 清理 Build 目录
gulp.task('cleanBuild', function (cb) {
    del('dist/**/*.*');
});

gulp.task('build', ['cleanBuild', 'sass', 'img-mini'], function () {
    console.log('>>>编译脚本完毕');
});

// SASS任务
gulp.task('sass', function () {
    //清理CSS文件夹下的所有文件。
    gulp.run('cleanCss');
    gulp.src([
            'src/sass/screen.scss'
        ])
        .pipe(sass().on('error', sass.logError))
        // 添加各种浏览器前缀
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(minifyCss())
        // 进行CSS压缩
        .pipe(gulp.dest('src/stylesheets'));
});
// 服务器
gulp.task('server', function () {
    gulp.run('sass');
    var files = [
        "src/images/**/*.png",
        "src/stylesheets/**/*.css",
        "src/javascripts/*.js",
        "html/*.html"
    ];
    browserSync.init(files, {
        server: {
            baseDir:'./',
            directory:true,
            index:'html/index.html'
        }
    });
    //监控SASS文件的变化
    gulp.watch('src/sass/*.scss', ['sass']);
    console.log("监控SASS文件中...");
});
//测试服务器
gulp.task('default', ['server']);
